import { ref } from 'vue'

import {getAppImageInfo} from '@/common/utils'
import type { AppContext } from './useCurrentInstance'

type Ctx = ReturnType<typeof uni.createCanvasContext>

type Option = {
	bgImgUrl?: string,
	canvasId : string,
	that : AppContext,
	width : number
	height : number
	bgWidth : number
	bgHeight : number
	drawIng : (ctx : Ctx) => Promise<unknown>
}



export const useCanvas = () => {
	const canvasImgUrl = ref('')
	const toTempFilePath = (that : AppContext, canvasId : string, width : number, height : number) => {
		return new Promise((resolve, reject) => {
			// 导出图片使用二倍图，防止图片不够清晰
			uni.canvasToTempFilePath({
				canvasId,
				fileType: 'png',
				width,
				height,
				// #ifndef APP
				destWidth: width*2,
				destHeight: height*2,
				// #endif
				success: res => {
					uni.hideLoading()
					canvasImgUrl.value = res.tempFilePath
					resolve(null)
				},
				fail: err => {
					console.log(err)
					reject(err)
				},
			},
				that
			)
		})

	}
	const canvasdraw = ({
		bgImgUrl,
		canvasId,
		that,
		width,
		height,
		bgWidth,
		bgHeight,
		drawIng,
	} : Option) => {
		return new Promise((resolve, reject) => {
			
			/* 获取绘图所需的上下文 */
			const ctx = uni.createCanvasContext(canvasId, that)
			// 清空画布内容
			ctx.draw(false,async () => {
				ctx.setFillStyle('#fff')
				ctx.fillStyle = '#fff'
				// 需填充满整个canvas，否则小程序下因为默认背景是黑色会导致未被填充的区域背景颜色是黑色
				ctx.fillRect(0, 0, width, height)
				if(bgImgUrl){
					const res = await getAppImageInfo(bgImgUrl)
					
					ctx.drawImage(res.path, 0, 0, bgWidth, bgHeight)
				}
				await drawIng(ctx)
				ctx.draw(false,() => {
					toTempFilePath(that, canvasId, width, height).then(() => {
						resolve(null)
					}).catch(err => {
						reject(err)
					})
				})
				
			}) 
			
			

		})

	}

	return {
		canvasdraw,
		canvasImgUrl
	}
}